package com.travel.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.travel.common.es.TicketEsModel;
import com.travel.search.config.TravelElasticsearchConfig;
import com.travel.search.constant.EsConstant;
import com.travel.search.service.TicketSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class TicketSaveServiceImpl implements TicketSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 保存票务信息到es中
     * @param ticketEsModel
     * @return
     */
    @Override
    public boolean ticketSave(TicketEsModel ticketEsModel) throws IOException {
        //1.给es中建立索引，建立映射关系

        //2.给es中保存这些数据
        BulkRequest bulkRequest = new BulkRequest();
        //2.1 构建请求保存
        IndexRequest indexRequest = new IndexRequest(EsConstant.TICKET_INDEX);
        indexRequest.id(ticketEsModel.getSpuId().toString());
        String s = JSON.toJSONString(ticketEsModel);
        indexRequest.source(s, XContentType.JSON);

        //2.2 把多条操作放入一个bulkRequest中 统一保存
        bulkRequest.add(indexRequest);

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, TravelElasticsearchConfig.COMMON_OPTIONS);

        //b：是否有异常 true：有 false：无
        boolean b = bulk.hasFailures();
        return b;

    }
}
